package com.xyh.flowershop.strategy;

import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xyh.flowershop.constant.CacheConstant;
import com.xyh.flowershop.domain.User;
import com.xyh.flowershop.enums.LoginEnum;
import com.xyh.flowershop.exceptions.custom.BizException;
import com.xyh.flowershop.vo.req.user.LoginUser;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Optional;

/**
 * @author 小约翰可汗
 * @className AccountLogin
 * @createTime 2024/7/1412:36
 */
@Component
public class AccountLogin extends AbstractLogin {


    /**
     * 后续整体整合
     * @param
     * @return
     */
//    @Override
//    public String wxLogin(String code) {
//        return null;
//    }

    @Override
    public String login(LoginUser loginUser) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        if(Objects.isNull(loginUser.getAccount()) || Objects.isNull(loginUser.getLoginToken())){
            throw new BizException("用户名或密码不能为空");
        }
        wrapper.eq(User::getAccount, loginUser.getAccount());
        User user = userService.getOne(wrapper);
        Optional.ofNullable(user).orElseThrow(() -> new BizException("用户不存在"));
        if(MD5.create().digestHex(loginUser.getLoginToken()).equals(user.getPassword())){
            String token = creatToken(user.getId());
            redisCache.setCacheObject(CacheConstant.LOGIN_PREFIX + user.getId(), token);
            return token;
        }
        throw new BizException("用户名或密码错误");
    }

    @Override
    protected Integer getType() {
        return LoginEnum.ACCOUNT_LOGIN.getCode();
    }
}
